package com.heima.wemedia.service.impl;

import apis.article.IArticleClient;
import com.alibaba.fastjson.JSON;
import com.heima.common.exception.CustomException;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.CommentArticleVo;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.CommentDto;
import com.heima.model.wemedia.dtos.CommentRepayDto;
import com.heima.wemedia.pojo.ApComment;
import com.heima.model.wemedia.dtos.ManageDto;
import com.heima.wemedia.pojo.ApCommentRepay;
import com.heima.wemedia.service.ManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ManageServiceImpl implements ManageService {

    /**
     * @param dto
     * @description: 回复评论
     * @param: dto
     * @return: com.heima.model.common.dtos.ResponseResult
     * @author: liyong
     * @date: 2023/06/29 15:51
     */
    @Override
    public ResponseResult commentRepay(CommentRepayDto dto) {
        if (Objects.isNull(dto) || Objects.isNull(dto.getCommentId()) || Objects.isNull(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        System.out.println("dto = " + dto);
        Query query = new Query(Criteria.where("id").is(dto.getCommentId()));
        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);

        if (Objects.isNull(apComment)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        ApCommentRepay apCommentRepay = ApCommentRepay.builder()
                .authorId(apComment.getAuthorId())
                .authorName(apComment.getAuthorName())
                .commentId(dto.getCommentId())
                .content(dto.getContent())
                .createTime(new Date())
                .updateTime(new Date())
                .build();
        mongoTemplate.save(apCommentRepay);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 分页查看文章的评论概览
     *
     * @param dto
     * @description:
     * @param: dto
     * @return: com.heima.model.common.dtos.ResponseResult
     * @author: liyong
     * @date: 2023/06/28 15:59
     */
    @Override
    public PageResponseResult manage(ManageDto dto) {

        if (Objects.isNull(dto)) {
            PageResponseResult pageResponseResult = new PageResponseResult();
            return pageResponseResult;
        }
        dto.checkParam();
        System.out.println("dto.getPage() = " + dto.getPage());
        System.out.println("dto.getSize() = " + dto.getSize());
        System.out.println("dto.getBeginDate() = " + dto.getBeginDate());
        System.out.println("dto.getEndDate() = " + dto.getEndDate());

        PageResponseResult responseResult = articleClient.pageCommentArticle(dto);

        List<CommentArticleVo> commentArticleVos = JSON.parseArray(JSON.toJSONString(responseResult.getData()), CommentArticleVo.class);
        //System.out.println("commentArticleVos = " + commentArticleVos);
        if (Objects.isNull(commentArticleVos)) {
            PageResponseResult pageResponseResult = new PageResponseResult();
            pageResponseResult.setErrorMessage("数据不存在");
            return pageResponseResult;
        }
        commentArticleVos.forEach(e -> {
            System.out.println("e.getId() = " + e.getId());
            System.out.println("e.getTitle() = " + e.getTitle());
            System.out.println("e.getComments() = " + e.getComments());
            System.out.println("e.getIsComment() = " + e.getIsComment());
            System.out.println("e.getCreatedTime() = " + e.getCreatedTime());

        });
        commentArticleVos.forEach(commentArticleVo -> {
            System.out.println("commentArticleVo.getId() = " + commentArticleVo.getId());
            Query query = new Query(Criteria.where("entryId").is(commentArticleVo.getId()));
            List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
            System.out.println("apComments = " + apComments);
            commentArticleVo.setComments(apComments.size());
        });
        responseResult.setData(commentArticleVos);

        return responseResult;
    }

    /**
     * @param dto
     * @description: 文章开启或关闭评论
     * @param: dto
     * @return: com.heima.model.common.dtos.ResponseResult
     * @author: liyong
     * @date: 2023/06/28 21:33
     */
    @Override
    public ResponseResult updateStatus(CommentDto dto) {
        System.out.println("dto = " + dto);
        if (Objects.isNull(dto) || Objects.isNull(dto.getArticleId()) || Objects.isNull(dto.getOperation()) || (dto.getOperation() != 0 && dto.getOperation() != 1)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        try {
            articleClient.updateStatus(dto);

            if (dto.getOperation() == 0) {
                System.out.println("mongo ......");
                System.out.println("dto.getArticleId() = " + dto.getArticleId());
                Query query = new Query(Criteria.where("entryId").is(dto.getArticleId()));
                mongoTemplate.remove(query, ApComment.class);
            }

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    /**
     * @param dto
     * @description: 查看文章评论列表
     * @param: dto
     * @return: com.heima.model.common.dtos.ResponseResult
     * @author: liyong
     * @date: 2023/06/29 14:45
     */
    @Override
    public ResponseResult list(CommentDto dto) {


        List<ApComment> apComments = mongoTemplate.find(new Query(Criteria.where("entryId").is(dto.getArticleId())), ApComment.class);
        List<Map<String, Object>> commentAndRepays = new ArrayList<>();
        if (apComments.size() > 0) {
            apComments.stream().parallel().forEach(
                    apComment -> {
                        HashMap<String, Object> data = new HashMap<>();
                        data.put("apComments", apComment);
                        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(new Query(Criteria.where("commentId").is(apComment.getId())), ApCommentRepay.class);
                        if (apCommentRepays.size() > 0) {
                            apCommentRepays.stream().sorted(new Comparator<ApCommentRepay>() {
                                @Override
                                public int compare(ApCommentRepay o1, ApCommentRepay o2) {
                                    return (int) (o2.getUpdateTime().getTime() - o1.getUpdateTime().getTime());
                                }
                            });
                            data.put("apCommentRepays", apCommentRepays);
                        }
                        commentAndRepays.add(data);
                    }
            );
        }

        return ResponseResult.okResult(commentAndRepays);
    }
}
